package cn.com.nes.site.service.workOrder.impl;

import cn.com.nes.common.exception.IllegalBusinessException;
import cn.com.nes.common.util.CopyUtils;
import cn.com.nes.common.util.XzqhUtils;
import cn.com.nes.common.web.CommonResult;
import cn.com.nes.mybatis.agent.ope.entity.WorkOrderCancelRecord;
import cn.com.nes.mybatis.agent.ope.mapper.WorkOrderCancelRecordMapper;
import cn.com.nes.mybatis.agent.project.entity.TProject;
import cn.com.nes.mybatis.agent.system.entity.TUser;
import cn.com.nes.site.entity.em.workOrder.CancelWorkOrdersStatusEnum;
import cn.com.nes.site.service.project.TProjectService;
import cn.com.nes.site.service.system.region.XzqhService;
import cn.com.nes.site.service.system.user.SystemUserService;
import cn.com.nes.site.service.workOrder.WorkOrderCancelDetailService;
import cn.com.nes.site.service.workOrder.WorkOrderCancelRecordService;
import cn.com.nes.site.service.workOrder.bo.InsertCancelRecordBO;
import cn.com.nes.site.service.workOrder.bo.QueryCancelRecordsPageBO;
import cn.com.nes.site.service.workOrder.dto.WorkOrderCancelRecordsDTO;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 工单批量撤销记录(WorkOrderCancelRecord)表服务实现类
 */
@Service
public class WorkOrderCancelRecordServiceImpl extends ServiceImpl<WorkOrderCancelRecordMapper, WorkOrderCancelRecord> implements WorkOrderCancelRecordService {

    @Resource
    private WorkOrderCancelDetailService workOrderCancelDetailService;

    @Resource
    private SystemUserService systemUserService;

    @Resource
    private TProjectService tProjectService;

    @Resource
    private XzqhService xzqhService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertCancelRecord(InsertCancelRecordBO bo) {
        // 保存撤销工单记录主表
        WorkOrderCancelRecord cancelRecord = new WorkOrderCancelRecord();
        BeanUtils.copyProperties(bo, cancelRecord);
        cancelRecord.setCompanyId(bo.getOperateUserCompanyId());
        cancelRecord.setStatus(String.join(",", bo.getWorkOrderStatusSet()));
        cancelRecord.setDeleted(false);
        cancelRecord.setGmtCreateId(bo.getOperateUserId());
        cancelRecord.setGmtCreate(bo.getOperateDate());
        cancelRecord.setGmtModifiedId(bo.getOperateUserId());
        cancelRecord.setGmtModified(bo.getOperateDate());

        int rows = this.baseMapper.insert(cancelRecord);
        if (rows < 1) {
            throw new IllegalBusinessException("新增撤销工单记录失败!");
        }

        // 保存撤销工单记录子表
        if (CollectionUtil.isNotEmpty(bo.getInsertCancelDetailBOList())) {
            workOrderCancelDetailService.insertCancelDetail(cancelRecord.getId(), bo.getInsertCancelDetailBOList());
        }
    }

    @Override
    public CommonResult<?> queryCancelRecordPage(QueryCancelRecordsPageBO queryBO) {
        // 准备返回数据
        Page<WorkOrderCancelRecordsDTO> resultPage = new Page<>(queryBO.getPageid(), queryBO.getPagesize());
        // 组装查询条件
        QueryWrapper<WorkOrderCancelRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("company_id", queryBO.getOperateUserCompanyId());
        queryWrapper.eq("deleted", false);
        if (ObjectUtil.isNotNull(queryBO.getStartTime())) {
            queryWrapper.ge("gmt_create", queryBO.getStartTime());
        }
        if (ObjectUtil.isNotNull(queryBO.getEndTime())) {
            queryWrapper.le("gmt_create", queryBO.getEndTime());
        }
        if (StrUtil.isNotBlank(queryBO.getAreaCode())) {
            queryWrapper.likeRight("area_code", XzqhUtils.getRegionCodePrefix(queryBO.getAreaCode()));
        }
        if (StrUtil.isNotBlank(queryBO.getProjectName())) {
            Set<Long> projectIdSet = tProjectService.getProjectIdSet(queryBO.getOperateUserCompanyId(), queryBO.getProjectName(), "", "");
            if (CollectionUtil.isEmpty(projectIdSet)) {
                resultPage.setRecords(new ArrayList<>());
                return CommonResult.page(resultPage);
            }
            queryWrapper.in("project_id", projectIdSet);
        }
        if (StrUtil.isNotBlank(queryBO.getCreateUserName())) {
            Set<Long> userIdSet = systemUserService.getUserIdSet(queryBO.getOperateUserCompanyId(), queryBO.getCreateUserName());
            if (CollectionUtil.isEmpty(userIdSet)) {
                resultPage.setRecords(new ArrayList<>());
                return CommonResult.page(resultPage);
            }
            queryWrapper.in("gmt_create_id", userIdSet);
        }
        queryWrapper.orderByDesc("gmt_create");
        // 准备分页参数
        Page<WorkOrderCancelRecord> page = new Page<>(queryBO.getPageid(), queryBO.getPagesize());
        // 执行查询语句
        IPage<WorkOrderCancelRecord> workOrderCancelRecordIPage = this.baseMapper.selectPage(page, queryWrapper);
        // 获取返回结果并转换类型
        List<WorkOrderCancelRecordsDTO> list = CopyUtils.copyList(workOrderCancelRecordIPage.getRecords(), WorkOrderCancelRecordsDTO.class);
        // 设置返回值
        for (WorkOrderCancelRecordsDTO recordsDTO : list) {
            TUser createUser = systemUserService.getUserInfoByUserId(String.valueOf(recordsDTO.getGmtCreateId()));
            TProject projectDetail = tProjectService.getProjectDetail(recordsDTO.getProjectId());

            recordsDTO.setCreateUserName(ObjectUtil.isNull(createUser) ? StrUtil.EMPTY : createUser.getNickName());
            recordsDTO.setProjectName(ObjectUtil.isNull(projectDetail) ? StrUtil.EMPTY : projectDetail.getProjectName());
            recordsDTO.setAreaName(xzqhService.getAreaName(recordsDTO.getAreaCode()));
            recordsDTO.setStatusName(CancelWorkOrdersStatusEnum.getStatusName(recordsDTO.getStatus()));
        }
        // 准备返回数据
        resultPage.setRecords(list);
        return CommonResult.page(resultPage);
    }
}
